#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using pii = pair<int, int>;
#define rep(i, a, b) for (int i = (a); i <= (b); i++)
#define per(i, a, b) for (int i = (a); i >= (b); i--)
#define endl '\n'
const int N = 2e6 + 5;

int n, n2;
int a[N];
int dq[N], head, tail;
bool cmp(int i, int j) { return a[i] > a[j]; }
void solve() {
  cin >> n;
  rep(i, 1, n) cin >> a[i];
  rep(i, 1, n) a[i + n] = a[i];
  n2 = n * 2;
  ll ans = 0;
  per(i, n2, 1) {
    while (head < tail && dq[head] >= i + n) head++;
    if (i <= n) {
      int j = lower_bound(dq + head, dq + tail, i, cmp) - dq;
      if (j > head) j--;
      // cout << i << ' ' << head << ' ' << tail << ' ' << tail - j << endl;
      ans += tail - j;
    }
    while (head < tail && a[dq[tail - 1]] < a[i]) tail--;
    dq[tail++] = i;
  }
  int mx = 0, cnt1 = 0;
  rep(i, 1, n) {
    if (mx < a[i])
      mx = a[i], cnt1 = 1;
    else if (mx == a[i])
      cnt1++;
  }
  int mn = 0, cnt2 = 0;
  rep(i, 1, n) {
    if (a[i] == mx) continue;
    if (mn < a[i])
      mn = a[i], cnt2 = 1;
    else if (mn == a[i])
      cnt2++;
  }
  if (cnt1 == 1)
    ans -= cnt2;
  else
    ans -= 1ll * cnt1 * (cnt1 - 1) / 2;
  cout << ans;
  return;
}

int main() {
  ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
  int t = 1;
  while (t--) solve();
  return 0;
}